package org.zhangchao.poi.excel.interceptor;

import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Row;

/**
 * Excel 拦截器栈
 * 
 * @author zhangchao
 * 
 */
public class ExcelHandlerInterceptorStack implements ExcelHandlerInterceptor {

	/** 拦截器集合 */
	private List<ExcelHandlerInterceptor> excelHandlerInterceptors;

	private int index;

	public ExcelHandlerInterceptorStack() {
		excelHandlerInterceptors = new ArrayList<ExcelHandlerInterceptor>();
	}

	public ExcelHandlerInterceptorStack(
			List<ExcelHandlerInterceptor> excelHandlerInterceptors) {
		this.excelHandlerInterceptors = excelHandlerInterceptors;
	}

	//@Override
	public void handler(Row row, MakeHandler makeHandler,
			ExcelHandlerInterceptorStack handlerStack) {
		if (null == excelHandlerInterceptors
				|| excelHandlerInterceptors.size() == 0
				|| index == excelHandlerInterceptors.size()) {
			index = 0;
			return;
		}
		ExcelHandlerInterceptor excelHandlerInterceptor = excelHandlerInterceptors
				.get(index);
		index++;
		if (excelHandlerInterceptor instanceof ExcelHandlerInterceptorStack) {
			ExcelHandlerInterceptorStack excelHandlerInterceptorStack = (ExcelHandlerInterceptorStack) excelHandlerInterceptor;
			excelHandlerInterceptorStack
					.handler(row, makeHandler, excelHandlerInterceptorStack);
		} else {
			excelHandlerInterceptor.handler(row, makeHandler, handlerStack);
		}
	}

	public List<ExcelHandlerInterceptor> getExcelHandlerInterceptors() {
		return excelHandlerInterceptors;
	}

	public void setExcelHandlerInterceptors(
			List<ExcelHandlerInterceptor> excelHandlerInterceptors) {
		this.excelHandlerInterceptors = excelHandlerInterceptors;
	}

	public ExcelHandlerInterceptorStack add(
			ExcelHandlerInterceptor excelHandlerInterceptor) {
		excelHandlerInterceptors.add(excelHandlerInterceptor);
		return this;
	}

	public ExcelHandlerInterceptorStack remove(int index) {
		excelHandlerInterceptors.remove(index);
		return this;
	}

}
